package tool

import (
	"bytes"
	"fmt"
	"strings"
	"text/template"
)

type Field struct {
	Name    string
	Type    string
	Comment string
}
type Entity struct {
	Package   string
	Name      string
	ShortName string
	Fields    []Field
}
type ValueStruct struct {
	Model    string
	CollID   string
	CollName string
	Package  string
	Entitys  []Entity
}

var collnameTplStr = `

type coll{{.Obj.Model}} struct {
	{{.Obj.Model}}ID string  {{$.QF}}bson:"_id" {{$.QF}}
	{{range .Obj.Entitys }}{{range .Fields}}{{.Name}} {{.Type}} {{$.QF}}bson:"{{scc .Name}},omitempty"{{$.QF }}  //{{.Comment}}
	{{end}}{{end}}
}

func (c coll{{.Obj.Model}}) CollID() string {
	return c.{{.Obj.CollID}}
}
func (coll{{.Obj.Model}}) CollName() string {
	// TODO: 这里可以提取为常量
	return collName{{.Obj.Model}}
}
{{range .Obj.Entitys }}
func (c *coll{{$.Obj.Model}}) Full{{.ShortName}}(e {{.Package}}.{{.Name}}) {
	{{range .Fields}}c.{{.Name}} = e.{{.Name}}
	{{end}}
}
func (c coll{{$.Obj.Model}}) To{{.ShortName}}()  {{.Package}}.{{.Name}} {
	return {{.Package}}.{{.Name}}{
		{{range .Fields}}{{.Name}} : c.{{.Name}},
		{{end}}
	}
}
{{end}}

func (c coll{{$.Obj.Model}}) ToAggregate() ddd.Aggregate {
	return c.To{{.Obj.Model}}Aggregate()
}
func (c coll{{$.Obj.Model}}) To{{.Obj.Model}}Aggregate() *{{.Obj.Package}}.{{.Obj.Model}}Aggregate {
	return &{{.Obj.Package}}.{{.Obj.Model}}Aggregate{
		{{range .Obj.Entitys }}
			{{.Name}}: c.To{{.ShortName}}(),
		{{end}}
	}
}
`
var (
	tpl = template.Must(template.New("").Funcs(template.FuncMap{
		"scc": ToSmallCamelCase,
	}).Parse(collnameTplStr))
)

func ToSmallCamelCase(s string) string {
	return strings.ToLower(s[0:1]) + s[1:]
}
func CreateMongoRepoColl(d ValueStruct) string {
	b := bytes.NewBuffer(nil)
	err := tpl.Execute(b, map[string]interface{}{
		"Obj": d,
		"QF":  "`",
	})
	if err != nil {
		fmt.Println(err)
	}
	return string(b.Bytes())
}
